<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import { ref, watch } from 'vue';

import { message } from 'ant-design-vue';

interface Room {
  id: string;
  number: string;
  type: string;
  status: string;
  capacity: number;
  occupied: number;
  handCard?: string;
}

interface Props {
  visible: boolean;
  room?: null | Room;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const formData = ref({
  roomNumber: '',
  handCard: '',
  items: [] as Array<{ name: string; price: number; quantity: number }>,
  totalAmount: 0,
  notes: '',
});

const itemColumns = [
  { title: '项目名称', dataIndex: 'name', key: 'name' },
  { title: '单价', dataIndex: 'price', key: 'price' },
  { title: '数量', dataIndex: 'quantity', key: 'quantity' },
  {
    title: '小计',
    key: 'subtotal',
    customRender: ({ record }: any) => record.price * record.quantity,
  },
  { title: '操作', key: 'action' },
];

const rules = {
  items: [{ required: true, message: '请添加消费项目' }],
};

// 监听房间变化
watch(
  () => props.room,
  (room) => {
    if (room) {
      formData.value = {
        roomNumber: room.number,
        handCard: room.handCard || '',
        items: [],
        totalAmount: 0,
        notes: '',
      };
    }
  },
  { immediate: true },
);

// 计算总金额
watch(
  () => formData.value.items,
  (items) => {
    formData.value.totalAmount = items.reduce(
      (sum, item) => sum + item.price * item.quantity,
      0,
    );
  },
  { deep: true },
);

const addItem = () => {
  formData.value.items.push({
    name: '',
    price: 0,
    quantity: 1,
  });
};

const removeItem = (index: number) => {
  formData.value.items.splice(index, 1);
};

const handleOk = async () => {
  try {
    await formRef.value?.validate();

    // 这里调用入账API
    message.success('入账成功');
    emit('update:visible', false);
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<template>
  <a-modal
    :open="visible"
    title="入账"
    width="500px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:open="(val) => emit('update:visible', val)"
  >
    <a-form :model="formData" :rules="rules" ref="formRef" layout="vertical">
      <a-form-item label="房间号" name="roomNumber">
        <a-input v-model:value="formData.roomNumber" disabled />
      </a-form-item>

      <a-form-item label="开房手牌" name="handCard">
        <a-input v-model:value="formData.handCard" disabled />
      </a-form-item>

      <a-form-item label="消费项目" name="items">
        <a-table
          :columns="itemColumns"
          :data-source="formData.items"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'action'">
              <a-button type="link" size="small" @click="removeItem(index)">
                删除
              </a-button>
            </template>
          </template>
        </a-table>
        <a-button type="dashed" block @click="addItem" style="margin-top: 8px">
          添加消费项目
        </a-button>
      </a-form-item>

      <a-form-item label="总金额" name="totalAmount">
        <a-input-number
          v-model:value="formData.totalAmount"
          :min="0"
          :precision="2"
          style="width: 100%"
          disabled
        />
      </a-form-item>

      <a-form-item label="备注" name="notes">
        <a-textarea
          v-model:value="formData.notes"
          placeholder="请输入备注"
          :rows="3"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
